import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref('')
  const userInfo = ref(null)
  const permissions = ref([])

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    // 可以同时保存到localStorage
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    // 可以同时保存到localStorage
    if (info) {
      localStorage.setItem('userInfo', JSON.stringify(info))
    } else {
      localStorage.removeItem('userInfo')
    }
  }

  // 设置权限列表
  const setPermissions = (perms) => {
    permissions.value = perms || []
    // 可以同时保存到localStorage
    if (perms && perms.length > 0) {
      localStorage.setItem('permissions', JSON.stringify(perms))
    } else {
      localStorage.removeItem('permissions')
    }
  }

  // 清除用户数据
  const clearUserData = () => {
    token.value = ''
    userInfo.value = null
    permissions.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('permissions')
  }

  // 从localStorage恢复数据
  const restoreFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedPermissions = localStorage.getItem('permissions')

    if (storedToken) {
      token.value = storedToken
    }
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
      } catch (e) {
        console.error('Failed to parse userInfo from localStorage:', e)
      }
    }
    if (storedPermissions) {
      try {
        permissions.value = JSON.parse(storedPermissions)
      } catch (e) {
        console.error('Failed to parse permissions from localStorage:', e)
      }
    }
  }

  // 检查是否有指定权限
  const hasPermission = (perm) => {
    if (!permissions.value || permissions.value.length === 0) {
      return false
    }
    
    // 检查完全匹配
    if (permissions.value.includes(perm)) {
      return true
    }
    
    // 检查通配符权限
    const wildcardPerm = perm.split(':').slice(0, -1).join(':') + ':*'
    if (permissions.value.includes(wildcardPerm)) {
      return true
    }
    
    // 检查超级管理员权限
    if (permissions.value.includes('admin:*') || permissions.value.includes('*')) {
      return true
    }
    
    return false
  }

  // 检查是否有多个权限中的任意一个
  const hasAnyPermission = (perms) => {
    return perms.some(perm => hasPermission(perm))
  }

  // 检查是否有所有指定权限
  const hasAllPermissions = (perms) => {
    return perms.every(perm => hasPermission(perm))
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 方法
    setToken,
    setUserInfo,
    setPermissions,
    clearUserData,
    restoreFromStorage,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions
  }
}) 